package com.egdigital.allzic.ui.activity;

import java.util.List;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.IBinder;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.actionbarsherlock.app.SherlockActivity;
import com.android.volley.VolleyError;
import com.egdigital.allzic.ApplicationGlobal;
import com.egdigital.allzic.R;
import com.egdigital.allzic.data.json.JsonCallBack;
import com.egdigital.allzic.data.json.JsonParserSimple;
import com.egdigital.allzic.data.json.JsonParserUpdate;
import com.egdigital.allzic.data.json.VolleyManager;
import com.egdigital.allzic.data.object.Station;
import com.egdigital.allzic.data.object.Updater;
import com.egdigital.allzic.service.ServiceStreaming;
import com.egdigital.allzic.ui.ExpandableHeightGridView;
import com.egdigital.allzic.ui.adapter.AdapterGridHome;
import com.egdigital.allzic.utils.AppRater;
import com.egdigital.allzic.utils.NetworkManager;
import com.egdigital.allzic.utils.Utils;

import fr.nomeo.AppsPanel;

public class ActivityHome extends SherlockActivity implements OnItemClickListener, OnClickListener, JsonCallBack {

	private static final String			TAG						= ActivityHome.class.getSimpleName();	// log
	//
	public static final int				CHAR_MIN_BEFORE_SEARCH	= 1;
	public static final String			EXTRA_SHORTCUT			= "extra_tab";
	private JsonParserSimple			mJsonParser;
	private boolean						mAutoCompletionEngoing	= false;
	//
	private ExpandableHeightGridView	mGrid;
	private AdapterGridHome				mAdapter;
	private ImageButton					mSearchButton;
	private ImageButton					mCrossButton;
	private AutoCompleteTextView		mSearchAutoCompletion;
	private RelativeLayout				mIncludeSearchLayout;
	// service streaming
	protected ServiceStreaming			mServiceRadio;
	protected ServiceConnection			mServiceConnexionRadio;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		this.setVolumeControlStream(AudioManager.STREAM_MUSIC); // allow music volume
		// layout
		setContentView(R.layout.activity_home);
		// close keyboard
		closeKb();
		// views
		mGrid = (ExpandableHeightGridView) findViewById(R.id.activity_home_grid);
		mIncludeSearchLayout = (RelativeLayout) findViewById(R.id.activity_home_search); // get the include with parent layout
		mSearchButton = (ImageButton) mIncludeSearchLayout.findViewById(R.id.search_button);
		mSearchAutoCompletion = (AutoCompleteTextView) mIncludeSearchLayout.findViewById(R.id.search_text);
		mCrossButton = (ImageButton) mIncludeSearchLayout.findViewById(R.id.search_cross);
		// close Keyboard
		InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		inputManager.hideSoftInputFromWindow(mSearchAutoCompletion.getWindowToken(), 0);
		// adapter
		mAdapter = new AdapterGridHome(this);
		mGrid.setAdapter(mAdapter);
		mGrid.setExpanded(true);
		// listeners
		mGrid.setOnItemClickListener(this);
		mSearchButton.setOnClickListener(this);
		mCrossButton.setOnClickListener(this);
		setupSearchListener();
		// Analytics
		((ApplicationGlobal) ApplicationGlobal.getContext()).getTracker();
		// service streaming
		mServiceConnexionRadio = new ServiceConnection() { // streaming service

			@Override
			public void onServiceDisconnected(ComponentName name) {
				mServiceRadio = null; // clean up service instance
			}

			@Override
			public void onServiceConnected(ComponentName name, IBinder binder) {
				if (mServiceRadio == null) {
					mServiceRadio = (ServiceStreaming) ((ServiceStreaming.PlayerBinder) binder).getServiceInstance();
				}
			}
		};
		// bind radio service
		bindServices();
		// rater dialog
		AppRater.app_launched(this);
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onResume() {
		super.onResume();
		mJsonParser = JsonParserSimple.getInstance();
		VolleyManager.init(this);
		mJsonParser.initAndStartRequestQueue();
		mJsonParser.setJsonCallBack(this);
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		mJsonParser.stopRequestQueue();
		Utils.cancelToast();
		// unbind ultimatly stop radio service
		unbindAndStopServices();
		super.onDestroy();
	}

	@Override
	public void onBackPressed() {
		Utils.cancelToast();
		finish();
		super.onBackPressed();
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
		Utils.cancelToast();
		moveToMainActivity(true, position);
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
			case R.id.search_cross:
				mSearchAutoCompletion.setText("");
				break;
			case R.id.search_button:
				if (mSearchAutoCompletion.getText().length() > CHAR_MIN_BEFORE_SEARCH) {
					moveToSearchActivity(mSearchAutoCompletion.getText().toString(), true);
				}
				break;
		}
	}

	private void moveToMainActivity(boolean doAnimation, int whichTab) {
		Intent intent = new Intent(this, ActivityMain.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.putExtra(EXTRA_SHORTCUT, whichTab);
		startActivity(intent);
		if (doAnimation) {
			overridePendingTransition(R.anim.slide_in_right, R.anim.slide_to_behind);
		}
	}

	private void moveToSearchActivity(String search, boolean doAnimation) {
		// close Keyboard
		InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		inputManager.hideSoftInputFromWindow(mSearchAutoCompletion.getWindowToken(), 0);
		//
		Intent intent = new Intent(this, ActivitySearch.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.putExtra("search", search);
		startActivity(intent);
		if (doAnimation) {
			overridePendingTransition(R.anim.slide_in_right, R.anim.slide_to_behind);
		}
	}

	@Override
	public void downloadStarted() {
		mAutoCompletionEngoing = true;
	}

	@Override
	public void downloadPercent(int percent) {
		// do nothing
	}

	@Override
	public <T> void downloadCompleted(List<T> list) {
		mAutoCompletionEngoing = false;
		if (list != null && !list.isEmpty()) {
			ArrayAdapter<T> adapter = new ArrayAdapter<T>(this, android.R.layout.simple_list_item_1, list); // simple adapter for auto-completion
			mSearchAutoCompletion.setAdapter(adapter);
		}
	}

	@Override
	public void downloadEndedWithError(VolleyError error) {
		mAutoCompletionEngoing = false;
	}

	/**
	 * @param searchWord
	 *        a string to send to the server for search
	 */
	private void loadAutoCompletionList(String searchWord) {
		if (NetworkManager.isConnected(getApplicationContext())) {
			try {
				mJsonParser.extractJsonObjectData(getString(R.string.url_autocompletion) + searchWord + "/1");
			} catch (Exception e) {
			}
		}
	}

	private void setupSearchListener() {
		mSearchAutoCompletion.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// not used
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// not used
			}

			@Override
			public void afterTextChanged(Editable chars) {
				// update cross button
				RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mSearchAutoCompletion.getLayoutParams();
				if (chars.length() > 0) {
					mCrossButton.setVisibility(View.VISIBLE);
					params.addRule(RelativeLayout.LEFT_OF, R.id.search_cross);
				} else {
					mCrossButton.setVisibility(View.GONE);
					params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
				}
				params.addRule(RelativeLayout.RIGHT_OF, R.id.search_button);
				params.setMargins(0, 1, 1, 1);
				mSearchAutoCompletion.setLayoutParams(params);
				if (chars.length() > CHAR_MIN_BEFORE_SEARCH) {
					if (mAutoCompletionEngoing == false) {
						loadAutoCompletionList(chars.toString()); // process search
					}
				}
			}
		});
		mSearchAutoCompletion.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
				moveToSearchActivity(view.getText().toString(), true);
				return true;
			}
		});
		mSearchAutoCompletion.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) {
				String selection = (String) parent.getItemAtPosition(position);
				moveToSearchActivity(selection, true);
			}
		});
	}

	private void closeKb() {
		// Close keyboard
		InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
		// check if no view has focus:
		View v = this.getCurrentFocus();
		if (v == null)
			return;
		inputManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
	}

	/**
	 * Attach the {@link Service} to the activity so we can get an instance of it.
	 */
	public void bindServices() {
		if (mServiceConnexionRadio != null) {
			bindService(new Intent(ActivityHome.this, ServiceStreaming.class), mServiceConnexionRadio, 0);
		}
	}

	/**
	 * Detach the {@link Service} to the activity
	 */
	public void unbindAndStopServices() {
		if (mServiceConnexionRadio != null) {
			unbindService(mServiceConnexionRadio);
		}
		if (ServiceStreaming.isRunning()) {
			stopService(new Intent(ActivityHome.this, ServiceStreaming.class));
		}
	}
}
